// File: jmcomic-core/src/main/java/dev/jukomu/common/base/logger/LoggerFactory.java
package dev.jukomu.common.base.logger;

import dev.jukomu.common.base.registry.ShutdownHookManager;

import java.io.IOException;

/**
 * 对应Python的LoggerFactory，用于创建Logger实例。
 */
public class LoggerFactory {

    /**
     * 获取一个Logger实例。
     *
     * @param filepath         Logger管理的文件路径
     * @param loadAfterCreated 是否在创建后立即加载数据
     * @param saveAtExit       是否在JVM退出时自动保存数据
     * @return Logger实例
     * @throws IOException 如果加载失败
     */
    public static Logger<String> getLogger(String filepath, boolean loadAfterCreated, boolean saveAtExit) throws IOException {
        FileLogger logger = new FileLogger(filepath);

        // 创建后立即加载数据
        if (loadAfterCreated) {
            logger.load();
        }

        // 注册JVM Shutdown Hook
        if (saveAtExit) {
            ShutdownHookManager.register(() -> {
                try {
                    logger.save();
                } catch (IOException e) {
                    System.err.println("Failed to save logger data on exit for " + filepath + ": " + e.getMessage());
                    e.printStackTrace();
                }
            }, "LoggerSaveHook-" + filepath.hashCode()); // 使用文件路径的哈希作为Hook名称
        }

        return logger;
    }
}